package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    @SneakyThrows
    public String upload(MultipartFile file) {
//          获取bucket的名字
        String bucketName = minioProperties.getBucketName();
//        判断bucket是否存在，如果不存在就创建
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!b) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            //配置桶的相关策略
            String policy = """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
            //设置桶的策略
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
        }
        //设置文件的名称
        String fileName = UUID.randomUUID() + new SimpleDateFormat("yyyy-mm-dd").format(new Date()) + "-*-" + file.getOriginalFilename();

        //上传文件
        minioClient.putObject(PutObjectArgs
                .builder()
                .bucket(bucketName)
                .object(fileName)
                .contentType(file.getContentType())
                .stream(file.getInputStream(),file.getSize(),-1)
                .build()
                );
        //返回文件的访问地址
        String url = String.join("/",minioProperties.getEndpoint(),bucketName,fileName);
        return url;
    }
}
